<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="商户" prop="mchId">
        <el-select v-model="queryParams.mchId" clearable filterable placeholder="请选择商户" size="small">
          <el-option
            v-for="dept in deptList"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="dept.deptId"
          >
            <span style="float: left">{{ dept.deptName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入项目地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目负责人" prop="employeeId">
        <el-select v-model="queryParams.employeeId" clearable filterable placeholder="请选择公司负责人" size="small">
          <el-option
            v-for="user in userList"
            :key="user.dictValue"
            :label="user.dictLabel"
            :value="user.dictValue"
          >
            <span style="float: left">{{ user.dictLabel }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ user.dictValue }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目接口人" prop="clientContact">
        <el-input
          v-model="queryParams.clientContact"
          placeholder="请输入项目接口人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口人电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入接口人电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目所属公司" prop="companyId">
        <el-select v-model="queryParams.companyId" clearable filterable placeholder="请选择所属公司" size="small">
          <el-option
            v-for="company in companyList"
            :key="company.id"
            :label="company.shortName"
            :value="company.id"
          >
            <span style="float: left">{{ company.shortName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ company.id }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目所属工地" prop="worksiteId">
        <el-select v-model="queryParams.worksiteId" clearable filterable placeholder="请选择所属工地" size="small">
          <el-option
            v-for="worksite in worksiteList"
            :key="worksite.id"
            :label="worksite.name"
            :value="worksite.id"
          >
            <span style="float: left">{{ worksite.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ worksite.id }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择项目状态" clearable>
          <el-option
            v-for="dict in dict.type.crm_project_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预计开始时间">
        <el-date-picker
          v-model="daterangeStartTime"
          style="width: 335px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="预计结束时间">
        <el-date-picker
          v-model="daterangeEstimatedEndTime"
          style="width: 335px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 335px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hrcrm:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hrcrm:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hrcrm:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hrcrm:project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="商户" align="center" prop="mchId" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="dept in deptList">
            <span v-if="dept.deptId == scope.row.mchId">{{dept.deptName}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="name" width="150" show-overflow-tooltip />
      <el-table-column label="项目地址" align="center" prop="address" width="150" show-overflow-tooltip />
      <el-table-column label="负责人" align="center" prop="employeeId">
        <template slot-scope="scope">
          <span v-for="user in userList">
            <span v-if="user.dictValue == scope.row.employeeId">{{user.dictLabel}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="接口人" align="center" prop="clientContact" />
      <el-table-column label="接口人电话" align="center" prop="contactPhone" width="120" show-overflow-tooltip />
      <el-table-column label="所属公司" align="center" prop="companyId">
        <template slot-scope="scope">
          <span v-for="company in companyList">
            <span v-if="company.id == scope.row.companyId">{{company.shortName}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所属工地" align="center" prop="worksiteId" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="worksite in worksiteList">
            <span v-if="worksite.id == scope.row.worksiteId">{{worksite.name}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="项目状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_project_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="薪资单位" align="center" prop="salaryUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.salary_unit" :value="scope.row.salaryUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="单位薪资" align="center" prop="salaryRate" />
      <el-table-column label="时薪方式" align="center" prop="hourlyRateCalculation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.salary_calculation_method" :value="scope.row.hourlyRateCalculation"/>
        </template>
      </el-table-column>
      <el-table-column label="预计开始日期" align="center" prop="startTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计结束日期" align="center" prop="estimatedEndTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estimatedEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打卡时间范围" align="center" prop="signInBegin" width="155">
        <template slot-scope="scope">
          <span v-if="scope.row.signInBegin != null && scope.row.signInEnd != null">
            {{ scope.row.signInBegin }} 至 {{ scope.row.signInEnd }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hrcrm:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hrcrm:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" style="width: 95%;">
        <el-form-item label="商户" prop="mchId">
          <el-select v-model="form.mchId" clearable filterable placeholder="请选择商户">
            <el-option
              v-for="dept in deptList"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptId"
            >
              <span style="float: left">{{ dept.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="employeeId">
          <el-select v-model="form.employeeId" clearable filterable placeholder="请输入工地负责人">
            <el-option
              v-for="user in userList"
              :key="user.dictValue"
              :label="user.dictLabel"
              :value="user.dictValue"
            >
              <span style="float: left">{{ user.dictLabel }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.dictValue }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目接口人" prop="clientContact">
          <el-input v-model="form.clientContact" placeholder="请输入项目接口人" />
        </el-form-item>
        <el-form-item label="接口人电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入接口人电话" />
        </el-form-item>
        <el-form-item label="项目所属公司" prop="companyId">
          <el-select v-model="form.companyId" clearable filterable placeholder="请选择所属公司" size="small">
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.shortName"
              :value="company.id"
            >
              <span style="float: left">{{ company.shortName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ company.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目所属工地" prop="worksiteId">
          <el-select v-model="form.worksiteId" clearable filterable placeholder="请选择所属工地" size="small">
            <el-option
              v-for="worksite in worksiteList"
              :key="worksite.id"
              :label="worksite.name"
              :value="worksite.id"
            >
              <span style="float: left">{{ worksite.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ worksite.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.crm_project_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="薪资计算单位" prop="hourlyRateCalculation">
          <el-select v-model="form.salaryUnit" placeholder="请选择薪资计算单位" @change="changeHourlyRateCalculationDesc">
            <el-option
              v-for="dict in dict.type.salary_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位薪资" prop="salaryRate">
          <el-input-number :min="0" :max="500" v-model="form.salaryRate" placeholder="请输入项目时薪" :controls="false" />
        </el-form-item>
        <el-form-item label="时薪计算方式" prop="hourlyRateCalculation">
          <el-select v-model="form.hourlyRateCalculation" placeholder="请选择时薪计算方式" @change="changeHourlyRateCalculationDesc">
            <el-option
              v-for="dict in dict.type.salary_calculation_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          <span style="font-size: 11px; color: red; margin-left: 3px;">
            {{ hourlyRateCalculationDesc }}
          </span>
        </el-form-item>
        <el-form-item label="预计开始日期" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预计开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预计结束日期" prop="estimatedEndTime">
          <el-date-picker clearable
            v-model="form.estimatedEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预计结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="打卡时间范围">
          <el-time-picker clearable
                          v-model="form.signInBegin"
                          type="time"
                          value-format="HH:mm:ss"
                          placeholder="如07:00至次日02:00">
          </el-time-picker>
          至
          <el-time-picker clearable
                          v-model="form.signInEnd"
                          type="time"
                          value-format="HH:mm:ss"
                          placeholder="不超过24小时">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/hrcrm/project";
import {getInfo} from "@/api/login";
import {allDept} from "@/api/system/dept";
import {getUserList} from "@/api/system/user";
import {allCompany} from "@/api/hrcrm/company";
import {allWorksite} from "@/api/hrcrm/worksite";

export default {
  name: "Project",
  dicts: ['crm_project_status', 'salary_calculation_method', 'salary_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeStartTime: [],
      // 备注时间范围
      daterangeEstimatedEndTime: [],
      // 备注时间范围
      daterangeCreateTime: [],
      // 时薪计算方式说明
      hourlyRateCalculationDesc: null,

      // 二级部门列表
      deptList: [],
      // 是否部门领导
      isLeader: true,
      // 是否管理员
      isAdmin: false,
      userParams: [],
      // 用户列表
      userList: [],
      loginUserId: null,

      // 公司列表
      companyList: [],
      // 工地列表
      worksiteList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mchId: null,
        name: null,
        address: null,
        employeeId: null,
        clientContact: null,
        contactPhone: null,
        companyId: null,
        worksiteId: null,
        status: null,
        salaryUnit: null,
        salaryRate: null,
        hourlyRateCalculation: null,
        startTime: null,
        estimatedEndTime: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mchId: [
          { required: true, message: "商户ID不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        employeeId: [
          { required: true, message: "项目负责人不能为空", trigger: "blur" }
        ],
        clientContact: [
          { required: true, message: "项目接口人不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "接口人电话不能为空", trigger: "blur" }
        ],
        companyId: [
          { required: true, message: "项目所属公司不能为空", trigger: "blur" }
        ],
        worksiteId: [
          { required: true, message: "项目所属工地不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "项目状态不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "预计开始时间不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人姓名不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "更新人姓名不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getInfo().then(
        res => {
          if (!res.isAdmin && !res.isLeader) {
            this.isLeader = false;
          }
          if (res.isAdmin) {
            this.isAdmin = true;
          }
          //登录用户ID赋值
          this.loginUserId = res.user.userId;
          //拉取部门
          allDept().then(response => {
            this.deptList = response.data
            this.initUserList(this.deptList[0].deptId)
            this.initCompanyList(this.deptList[0].deptId)
            this.initWorksiteList(this.deptList[0].deptId)
            if(!this.isAdmin){
              this.queryParams.mchId.push(this.deptList[0].deptId);
            }
            this.getList();
          });
        })
    },
    /** 选中部门的Id*/
    initUserList(deptId) {
      this.userList=[];
      this.userParams.deptId=deptId
      if(!this.isLeader){
        this.userParams.userId=this.loginUserId;
      }
      getUserList(this.userParams).then(response => {
        this.userList = response.data;
      });
    },
    /** 公司列表 */
    initCompanyList(mchId) {
      allCompany('{"mchId": "' + mchId + '"}').then(response => {
        this.companyList = response.rows
      })
    },
    /** 工地列表 */
    initWorksiteList(mchId) {
      allWorksite('{"mchId": "' + mchId + '"}').then(response => {
        this.worksiteList = response.rows
      })
    },
    /** 查询项目信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
        this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0];
        this.queryParams.params["endStartTime"] = this.daterangeStartTime[1];
      }
      if (null != this.daterangeEstimatedEndTime && '' != this.daterangeEstimatedEndTime) {
        this.queryParams.params["beginEstimatedEndTime"] = this.daterangeEstimatedEndTime[0];
        this.queryParams.params["endEstimatedEndTime"] = this.daterangeEstimatedEndTime[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mchId: null,
        name: null,
        address: null,
        employeeId: null,
        clientContact: null,
        contactPhone: null,
        companyId: null,
        worksiteId: null,
        status: 'PROGRESS',
        salaryUnit: null,
        salaryRate: null,
        hourlyRateCalculation: null,
        startTime: null,
        estimatedEndTime: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.hourlyRateCalculationDesc = null
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartTime = [];
      this.daterangeEstimatedEndTime = [];
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProject(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目信息编号为"' + ids + '"的数据项？').then(function() {
        return delProject(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hrcrm/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
    changeHourlyRateCalculationDesc() {
      if (this.form.hourlyRateCalculation == 'ACCURATE') {
        this.hourlyRateCalculationDesc = '薪资计算精确到分钟';
      } else if (this.form.hourlyRateCalculation == 'QUARTER') {
        this.hourlyRateCalculationDesc = '01-15算整点，16-30算半点，30-44算半点，45-60是整点';
      } else if (this.form.hourlyRateCalculation == 'HALF') {
        this.hourlyRateCalculationDesc = '不满半小时忽略，超过半小时按一小时计算';
      } else if (this.form.hourlyRateCalculation == 'HOUR') {
        this.hourlyRateCalculationDesc = '不满一小时部分忽略';
      }
    },
  }
};
</script>
